//
//  HttpManager.swift
//  InfoAPP
//
//  Created by leeco on 2019/5/27.
//  Copyright © 2019 zsw. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON
import ObjectMapper
import HandyJSON
import RxSwift

class Config {
    static let requestAddress = "https://app.ngbbs.cn"
}

// MARK: - Response Models
struct ForumListResponse: Codable {
    let code: Int
    let msg: String?
    let list: [ResponseForumDetailListDataModel]?
    
    var isSuccess: Bool {
        return code == 100
    }
}

struct ForumListData: Codable {
    let list: [ResponseForumDetailListDataModel]?
    let total: Int?
    let page: Int?
    let step: Int?
}

// MARK: - Network Error
enum NetworkError: Error, LocalizedError {
    case invalidResponse
    case serverError(code: Int, message: String)
    case noData
    case decodingError
    case networkError(Error)
    
    var errorDescription: String? {
        switch self {
        case .invalidResponse:
            return "无效的响应"
        case .serverError(let code, let message):
            return "服务器错误 (\(code)): \(message)"
        case .noData:
            return "没有数据"
        case .decodingError:
            return "数据解析错误"
        case .networkError(let error):
            return "网络错误: \(error.localizedDescription)"
        }
    }
}

class HttpManager: NSObject {
    class var sharedInstance: HttpManager {
        
        struct Static {
            static var instance: HttpManager = HttpManager()
        }

        return Static.instance
    }
    
    //九宫格
    func getHomeClassify(success:@escaping (_ successd:Array<HomeClassifyModel>)->(),fail:(_ failed:Error)->()){
        
        AF.request( Config.requestAddress +  "/mag/info/v2/channel/channelConfigById?channel_id=1").responseJSON { (response) in
            
            if response.value != nil{
                
                switch response.result{
                    
                case.success(let json):
                    
                    let dict = json as! Dictionary<String,AnyObject>
                    
                    let data = dict["data"] as! Dictionary<String,AnyObject>
                    let operative_config = data["operative_config"] as! NSArray
                    let operativeDict = operative_config[3] as! Dictionary<String,AnyObject>
                    
                    let items = operativeDict["items"] as! NSArray
                    
                    let lists = Mapper<HomeClassifyModel>().mapArray(JSONArray: items as! [[String : Any]])
                    
                    success(lists)
                    
                    break
                case .failure(let error):
                    print("\(error)")
                    break
                    
                }
                
            }
            
        }
        
    }
    //顶部轮播图
    func getHomeCircle(success:@escaping (_ successd:Array<HomeCircle>)->(),fail:(_ failed:Error)->()){
        AF.request(Config.requestAddress + "/mag/operative/v1/ad/listNotEndByPlace?place=pic_slide_1486618172").responseJSON { (response) in
            
            if response.value != nil{
                
                switch response.result{
                    
                case.success(let json):
                    
                    let dict = json as! Dictionary<String,AnyObject>
                    
                    let list = dict["list"] as! Array<Any>
                    
                    let lists = Mapper<HomeCircle>().mapArray(JSONArray: list as! [[String : Any]])
                    
                    success(lists)
                    
                    break
                case .failure(let error):
                    print("\(error)")
                    break
                    
                }
                
            }
            
        }
        
        
    }

    
    func getIconNavigation(success:@escaping (_ successd:Icon_navigation)->(),fail:(_ failed:Error)->()){

        AF.request("https://app.ngbbs.cn/mag/info/v1/channel/channelConfigById?channel_id=1").responseJSON { (response) in

                if response.value != nil{
                    
                    switch response.result{
                    case.success(let json):

//                        print(JSON.init(arrayLiteral: json))
                        
                        
                        let dict = json as! Dictionary<String,AnyObject>
                        
                        let result = dict["data"]!["operative_config"] as! Array<Any>

                        let iconNavigation = result[2]

                        let icons = Mapper<Icon_navigation>().map(JSONObject: iconNavigation)!

                        success(icons)

                        break
                    case .failure(let error):
                        print("\(error)")
                        break
                        
                    }
                    
                }
            
        }
    }
    
    func getHomeList(patameter:Parameters, success:@escaping (_ successd:Array<HomeListModel>)->(),fail:(_ failed:Error)->()){
        
        AF.request(Config.requestAddress + "/mag/info/v2/channel/infoListByCatId?cat_id=2&channel_id=1&content_id=&is_app_first=-1&step=20&tab=0&uniqid=5af95dca461d2",parameters: patameter).responseJSON { (response) in
            if response.value != nil{
                
                switch response.result{
                case.success(let json):
                    
                    print(JSON.init(arrayLiteral: json))
                    
                    
                    let dict = json as! Dictionary<String,AnyObject>
                    //
                    let result = dict["list"] as! Array<Any>
                    //
                    //                            let iconNavigation = result[2]
                    //
                    let lists = Mapper<HomeListModel>().mapArray(JSONArray: result as! [[String : Any]])
                    //
                    success(lists)
                    
                    break
                case .failure(let error):
                    print("\(error)")
                    break
                    
                }
                
            }
            
        }
        
    }

    func getChannelDetail(patameter:Parameters, success:@escaping (_ successd:Array<ContentlistModel>)->(),fail:(_ failed:Error)->()) {
        AF.request("http://ali-news.showapi.com/newsList", parameters: patameter, headers: ["Authorization":"APPCODE 4c0aa04ae3a74d57996a169ae94c78e6"]).responseJSON { (response) in
            
            let dataArr: Array<ContentlistModel>
            if response.value != nil{
                
                switch response.result{
                case.success(let json):
                    
                    print(JSON.init(arrayLiteral: json))
                    
                    let dict = json as! Dictionary<String,AnyObject>
                    
                    let pagebean = dict["showapi_res_body"]!["pagebean"] as! Dictionary<String,AnyObject>
                    let contentlist = pagebean["contentlist"]
                    
                    dataArr = Mapper<ContentlistModel>().mapArray(JSONArray: contentlist as! [[String : Any]])
                    
                    success(dataArr)
                    
                    break
                case .failure(let error):
                    print("\(error)")
                    break
                    
                }
                
            }
        }
        
    }
    
    
    func getDatas(patameter:Parameters, success:@escaping (_ successd:Array<ContentlistModel>)->(),fail:(_ failed:Error)->()) {
        
        //请求接口数据
        AF.request("http://toutiao-ali.juheapi.com/toutiao/index", parameters: patameter, headers: ["Authorization":"APPCODE 4c0aa04ae3a74d57996a169ae94c78e6"]).responseJSON { (response) in
            if response.value != nil{
                
                switch response.result{
                case.success(let json):
                    
                    let dict = json as! Dictionary<String,AnyObject>
                    let result = dict["result"]!["data"]
                    
                    let  dataArr = Mapper<ContentlistModel>().mapArray(JSONArray: result as! [[String : Any]])
                    
                    success(dataArr)
                    
                    break
                case .failure(let error):
                    print("\(error)")
                    break
                    
                }
                
            }
        }
    }
    
    /// 响应数据结构
    struct ResponseCircleClassData: Decodable {
        let message: String
    }
    //逛论坛tab数据
    func getCircleClass(success:@escaping ( _ successd:Array<ResponseCircleClassModel>)->(),fail:(_ failed:Error)->()){
        AF.request(Config.requestAddress + "/mag/circle/v1/Circle/circleClassifyList").responseJSON { (response) in
            
            if response.value != nil{
                
                switch response.result {

                case.success(let json):
                    
                    let dict = json as! Dictionary<String,AnyObject>
                    
                    guard dict["code"] as! Int == 100 else {
                        success([])
                        return;
                    }
                    
                    let list = dict["list"] as! Array<Any>
                    
                    let lists = Mapper<ResponseCircleClassModel>().mapArray(JSONArray: list as! [[String : Any]])
                    
                    success(lists)
                    
                    break
                case .failure(let error):
                    print("\(error)")
                    break
                    
                }
                
            }
            
        }
        
        
    }
    
    //逛论坛tab--二级数据
    func getDetailCircleClass(patameter:Parameters, success:@escaping ( _ successd:Dictionary<String,AnyObject>)->(),fail:(_ failed:Error)->()){
        AF.request(Config.requestAddress + "/mag/circle/v2/forum/getCircleCatConfig",parameters: patameter).responseJSON { (response) in
            
            if response.value != nil{
                
                switch response.result {

                case.success(let json):
                    
                    let dict = json as! Dictionary<String,AnyObject>
                    
                    guard dict["code"] as! Int == 100 else {
                        success([:])
                        return;
                    }

                    success(dict)
                    
                    break
                case .failure(let error):
                    print("\(error)")
                    break
                    
                }
                
            }
            
        }
        
        
    }
/*
    //逛论坛tab--二级list数据
    func getDetailListDatas(patameter:Parameters, success:@escaping ( _ successd:Dictionary<String,AnyObject>)->(),fail:(_ failed:Error)->()){

        AF.request(Config.requestAddress + "/mag/circle/v2/forum/forumViewV2",parameters: patameter).responseJSON { (response) in
            
            if response.value != nil{
                
                switch response.result {

                case.success(let json):
                    
                    let dict = json as! Dictionary<String,AnyObject>
                    
                    guard dict["code"] as! Int == 100 else {
                        success([:])
                        return;
                    }

                    success(dict)
                    
                    break
                case .failure(let error):
                    print("\(error)")
                    break
                    
                }
                
            }
            
        }
        
        
    }*/
    
    // MARK: - Forum List API
        func getDetailListDatas(
            parameters: [String: String],
            completion: @escaping (Result<ForumListResponse, NetworkError>) -> Void
        ) {
            let url = Config.requestAddress + "/mag/circle/v2/forum/forumViewV2"
            
            AF.request(url, parameters: parameters)
                .validate()
                .responseDecodable(of: ForumListResponse.self) { response in
                    switch response.result {
                    case .success(let forumResponse):
                        // 检查业务状态码
                        guard forumResponse.isSuccess else {
                            let error = NetworkError.serverError(
                                code: forumResponse.code,
                                message: forumResponse.msg ?? "未知错误"
                            )
                            completion(.failure(error))
                            return
                        }
                        // 检查数据
                        guard let list = forumResponse.list else {
                            completion(.failure(.noData))
                            return
                        }
                        
                        completion(.success(forumResponse))
                        
                    case .failure(let error):
                        // 处理网络错误
                        if let afError = error as? AFError {
                            switch afError {
                            case .responseValidationFailed(let reason):
                                print("响应验证失败: \(reason)")
                            case .responseSerializationFailed(let reason):
                                print("响应序列化失败: \(reason)")
                            default:
                                print("网络请求失败: \(afError)")
                            }
                        }
                        
                        completion(.failure(.networkError(error)))
                    }
                    
                }
        }
    
}
// MARK: - Usage Examples
extension HttpManager {
    
    // MARK: - Modern Usage with Codable
    func fetchForumList(
        page: Int = 1,
        step: Int = 10,
        circleId: String,
        fid: String,
        completion: @escaping (Result<ForumListResponse, NetworkError>) -> Void
    ) {
        let parameters: [String: String] = [
            "p": "\(page)",
            "step": "\(step)",
            "circle_id": circleId,
            "fid": fid
        ]
        
        getDetailListDatas(parameters: parameters) { result in
            switch result {
            case .success(let data):
                
                completion(.success(data))
                
            case .failure(let error):
                completion(.failure(error))
            }
        }
    }
}
